package org.poem.client;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.google.common.collect.Lists;
import org.poem.CanalClientEntryVO;
import org.poem.CanalClientHeadEntityVO;
import org.poem.ExecTaskDetailPlanVO;
import org.poem.canal.CanalHandleEntry;
import org.poem.exec.register.CanalHandlerRegister;
import org.poem.exec.register.TaskRegisterFilter;
import org.poem.kafka.KafkaProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author poem
 */
@Service
public class CanalClient implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(CanalClient.class);

    @Autowired
    private ClientServiceConfig clientServiceConfig;

    @Autowired
    private KafkaProducer kafkaProducer;

    /**
     * 执行
     *
     * @param clientServiceConfig
     */
    private void main(ClientServiceConfig clientServiceConfig) {
        print(clientServiceConfig);
        String ip = clientServiceConfig.getIp();
        int port = clientServiceConfig.getPort();
        String userName = clientServiceConfig.getUser();
        String password = clientServiceConfig.getPassword();
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), "example", userName, password);
        int batchSize = 1000;
        int sleep = 100;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            logger.info("connect success!\r\n startup...");
            // 获取指定数量的数据
            while (true) {
                try {
                    Message message = connector.getWithoutAck(batchSize);
                    long batchId = message.getId();
                    int size = message.getEntries().size();
                    if (batchId == -1 || size == 0) {
                        // 等待时间
                        try {
                            Thread.sleep(sleep);
                        } catch (InterruptedException e) {
                            logger.error(e.getMessage(), e);
                        }
                    } else {
                        handleEntry(message.getEntries());
                    }
                    // 提交确认
                    connector.ack(batchId);
                } catch (Exception e) {
                    connector.rollback();
                }
            }
        } finally {
            connector.disconnect();
        }
    }

    /**
     * 处理生成的数据
     *
     * @param entrys 日志记录
     */
    private void handleEntry(List<CanalEntry.Entry> entrys) throws Exception {
        //循环每行binlog
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }
            CanalEntry.RowChange rowChage;
            try {
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e);
            }
            List<CanalClientEntryVO> entries = Lists.newArrayList();
            List<CanalClientEntryVO> before = Lists.newArrayList();
            //单条 binlog sql
            CanalEntry.EventType eventType = rowChage.getEventType();
            String sql = rowChage.getSql();
            //受影响 数据行
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                //获取字段值
                if (eventType == CanalEntry.EventType.DELETE) {
                    entries = convertEntry(rowData.getBeforeColumnsList());
                } else if (eventType == CanalEntry.EventType.INSERT) {
                    entries = convertEntry(rowData.getAfterColumnsList());
                    before = convertEntry(rowData.getBeforeColumnsList());
                } else {  //update
                    entries = convertEntry(rowData.getAfterColumnsList());
                    before = convertEntry(rowData.getBeforeColumnsList());
                }
            }
            CanalClientHeadEntityVO entity = new CanalClientHeadEntityVO(
                    eventType,
                    entry.getHeader().getLogfileName(),
                    entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(),
                    entry.getHeader().getTableName(),
                    Lists.newArrayList(sql),
                    entries, before);
            kafkaProducer.sendMessage(JSONObject.toJSONString(entity));
        }
    }

    /**
     * 装换成实体
     *
     * @param columns
     * @return
     */
    private static List<CanalClientEntryVO> convertEntry(List<CanalEntry.Column> columns) {
        List<CanalClientEntryVO> entries = Lists.newArrayList();
        CanalClientEntryVO entry;
        for (CanalEntry.Column column : columns) {
            entry = new CanalClientEntryVO();
            entry.setName(column.getName());
            entry.setValue(column.getValue());
            entry.setUpdated(column.getUpdated());
            entry.setKey(column.getIsKey());
            entry.setNullColumn(column.getIsNull());
            entry.setLength(column.getLength());
            entry.setMysqlType(column.getMysqlType());
            entries.add(entry);
        }
        return entries;
    }

    /**
     * 展示配置
     *
     * @param clientServiceConfig
     */
    private static void print(ClientServiceConfig clientServiceConfig) {
        logger.info("\nInit Canal Config  " +
                "\n\t\t [ip]:" + clientServiceConfig.getIp() +
                "\n\t\t [port]:" + clientServiceConfig.getPort() +
                "\n\t\t [user]:" + clientServiceConfig.getUser() +
                "\n\t\t [password]:" + clientServiceConfig.getPassword()
        );
    }

    /**
     * auto run
     *
     * @param args 参数
     * @throws Exception 执行错误执行
     */
    @Override
    public void run(String... args) throws Exception {
        //开启同步
        main(this.clientServiceConfig);
    }
}
